package com.iraeta.service.sys.impl;

import com.iraeta.dao.main.sys.RoleDao;
import com.iraeta.entity.main.PermissionType;
import com.iraeta.entity.main.Role;
import com.iraeta.entity.main.RolePermission;
import com.iraeta.service.sys.RoleService;
import com.iraeta.uitl.Util;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Resource
    RoleDao roleDao;

    @Transactional
    @Override
    public void addRole(Role role) {
        roleDao.insert(role);
        RolePermission rolePermission = new RolePermission(role.getId(), PermissionType.pingTaiLogin);
        roleDao.insertRolePermission(rolePermission);
    }

    @Override
    public void updateRole(Role role) {
        roleDao.updateByPrimaryKey(role);
    }

    @Override
    public void deleteRole(int id) {
        roleDao.deleteByPrimaryKey(id);
    }

    @Override
    public Role getRole(int id) {
        return roleDao.selectByPrimaryKey(id);
    }

    @Override
    public List<Role> getRoleByName(String roleName) {
        return roleDao.selectByRoleName(roleName);
    }

    /*userRole相关*/
    @Override
    public List<Role> listAllRole() {
        return roleDao.selectAllRole();
    }
    @Override
    public List<Role> listRoleByUserId(int userId) {
        return roleDao.selectRoleByUserId(userId);
    }


    /*role permission相关*/
    @Override
    public List<Integer> listRolePermission(int roleId) {
        return roleDao.selectRolePermission(roleId);
    }
    @Transactional
    @Override
    public void saveRolePermission(int roleId, List<Integer> permissionList) {
        for (Integer permissionId : permissionList) {
            if(roleDao.selectByRolePermission(roleId, permissionId) == null){
                RolePermission rolePermission = new RolePermission(roleId, permissionId);
                roleDao.insertRolePermission(rolePermission);
            }
        }
        String rolePermissionIdStr = Util.parseListToString(permissionList);
        roleDao.deleteRolePermissionIdStr(roleId, rolePermissionIdStr);
    }
}
